var gulp = require('gulp'),
    path = require("path"),
    minifycss = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    cache = require('gulp-cache'),
    gulpwebpack = require('gulp-webpack'),
    fileinclude = require('gulp-file-include'),
    htmlmin = require("gulp-htmlmin"),
    nodemon = require("gulp-nodemon"),
    glob = require("glob"),
    less = require("gulp-less");

function entries(){
    var obj={};
    function make(files){
        files.forEach(function(t,i){
            var k = path.relative("src/js/js/",t);
            obj[k.substr(0, k.length-3)] = [path.resolve(__dirname,t)];
        });
        return obj;
    }
    var a =  glob("src/js/js/**/*.js",{sync:true});
    var b =  make(a);

    return b;
}
gulp.task("html",function(){
    var options = {
        removeComments: true,
        collapseWhitespace: true,
        collapseBooleanAttributes: true,
        removeEmptyAttributes: true,
        removeScriptTypeAttributes: false,
        removeStyleLinkTypeAttributes: false,
        minifyJS: true,
        minifyCSS: true
    };
    return gulp.src('src/template/views/**/*.ejs')
        .pipe(fileinclude({
            prefix:"<@",
            suffix:"@>",
            basePath:"@file"
        }))
        .pipe(htmlmin(options))
        .pipe(gulp.dest("views/"));
});
gulp.task("clean",function(){
    return gulp.src(['views/','public/css','public/imgs','public/js'])
        .pipe(clean());
});
gulp.task("styles",function(){
    return gulp.src(['src/css/**/*.less','!src/css/*.less'])
        .pipe(less())
        .pipe(rename({suffix:".min"}))
    //    .pipe(minifycss())
        .pipe(gulp.dest("public/css"));
});
gulp.task('img', function() {
    return gulp.src('src/imgs/**/*')
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest('public/imgs'));
});
gulp.task("js",function(){
    return gulp.src("src/js/entry.js")
        .pipe(gulpwebpack({
            entry:entries(),
            //   "devtool":"source-map",
            output:{
                filename:'[name].js'
            }
        }))
      //  .pipe(uglify())
        .pipe(gulp.dest("public/js/"));
});
gulp.task("default",['clean'],function(){
  gulp.start("html","styles",'img','js','watch','start');
});
 gulp.task('watch', function() {
 gulp.watch('src/css/**/*.less', ['styles']);
 gulp.watch('src/js/**/*.js', ['js']);
 gulp.watch('src/imgs/**/*.*', ['img']);
 gulp.watch('src/template/**/*.ejs', ['html']) ;
 //  gulp.watch("services/**/*.js",["restart"])
 //  gulp.watch("routes/**/*.js",["restart"])
 //  gulp.watch("bin/**/*.js",["start"])
 });
gulp.task("restart",function(){
  var date = new Date();
  var gap = 500;
  setTimeout(function(){
    if(new Date()-date > gap){
      console.log("hello gap")
    }
  },300)
});
gulp.task("start",function(){
    nodemon({
        script:"bin/www\t1"
       , ext: 'js',
      ignore: [
            'src/',
            'node_modules/',
            'public/',
            'views/'
        ],
        watch: ['routes/','services/','utils/','bin/','app.js'],
      stdout:   true,
      readable: false,
      env: { 'NODE_ENV': 'development' }
    }).on('crash', function() {
        console.error('Application has crashed');
    })
});
